<template>
  <ProTable
    ref="tableRef"
    :fetchListApi="_fetchList"
    :columns="columns"
    row-key="versionId"
    :rowSelection="rowSelection"
  >
    <template #toolbars>
      <Space>
        <b-button icon="add" @click="onAdd()" code="firmwareVersion:add"
          >新增</b-button
        >
        <b-button
          icon="delete"
          @click="onDelete()"
          code="firmwareVersion:remove"
          :disabled="!selectRows.length"
          >删除</b-button
        >
      </Space>
    </template>
    <template #modelAlwaysVOS="{ record }">
      <Tree
        v-if="record.modelAlwaysVOS && record.modelAlwaysVOS.length"
        :tree-data="record.modelAlwaysVOS"
        :field-names="fileNames"
      />
    </template>
    <template #operation="{ record }">
      <b-button
        type="link"
        icon="detail"
        @click="onLook(record)"
        code="firmwareVersion:query"
        >查看</b-button
      >
      <span v-if="record.isAudit == '1'">
        <!-- <b-button
          icon="edit"
          type="link"
          @click="onUpdate(record)"
          code="firmwareVersion:edit"
        >
          编辑</b-button
        > -->

        <b-button
          icon="verify"
          type="link"
          @click="onPush(record)"
          :disabled="record.isEnable == '1'"
          code="firmwareVersion:check"
        >
          验证</b-button
        >
        <b-button
          icon="examine"
          type="link"
          @click="onAudit(record)"
          code="firmwareVersion:audit"
        >
          审核</b-button
        >
      </span>
      <span v-else>
        <b-button
          icon="activate"
          type="link"
          @click="onSwitch(record)"
          code="firmwareVersion:switch"
          >{{ record.isEnable == '0' ? '停用' : '启用' }}
        </b-button>
      </span>
    </template>
  </ProTable>
  <FormModal :items="items" wrapClassName="fireVersion_modal">
    <template #openAudit="{ formState, modalType }">
      <Audit :audit="auditInfo"></Audit>
    </template>
    <template #customFooter="{ visible, formState }">
      <div v-if="formState.isAudit == '0'"></div>
      <div v-else-if="modalType === 'info'">
        <b-button type="primary" @click="onUpdate" code="firmwareVersion:edit"
          >编辑</b-button
        >
      </div>
      <div v-else-if="modalType === 'audit'">
        <b-button type="primary" @click="onConfirm(visible)">通过</b-button>
      </div>
      <div v-else>
        <b-button type="primary" @click="onSubmit(formState, visible)"
          >确认</b-button
        >
        <b-button @click="onCancel(visible)">取消</b-button>
      </div>
    </template>
  </FormModal>
  <Modal
    v-model:open="openVerify"
    title="验证"
    :width="1200"
    :mask-closable="false"
    centered
    destroy-on-close
  >
    <Verify ref="verifyRef" :push="pushInfo" @pushUpdate="updateLog"></Verify>
    <template #footer>
      <!-- <b-button @click="openVerify = false">关闭</b-button> -->
      <b-button type="primary" @click="onVerify">验证</b-button>
    </template>
  </Modal>
  <Modal
    v-model:open="openUpdate"
    title="推送设备列表"
    :width="1200"
    :mask-closable="false"
    centered
    :footer="null"
    destroy-on-close
  >
    <Update :update="updateInfo"></Update>
  </Modal>
</template>

<script setup lang="tsx">
import { computed, onMounted, provide, ref } from 'vue';
import {
  Button,
  Col,
  Input,
  Modal,
  RadioButton,
  RadioGroup,
  Row,
  Space,
  Tag,
  Tree,
  TreeProps,
  TreeSelect,
  message,
} from 'ant-design-vue';
import { ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import { listToOption } from '@/utils/utils';
import {
  appUpdateTypeEnum,
  appUpdateTypeOption,
  auditEnum,
  enableStatusEnum,
  packageTypeEnum,
} from '@/constant/push';
import { getUpgradeDetail, modelTree, pullPackageList } from '@/api/config';
import {
  addFirmware,
  delFirmware,
  featchFirmwareList,
  firmSubmitAudit,
  firmUpdateStatus,
  getFirmwareInfo,
  updateFirmware,
} from '@/api/push';
import Audit from './components/Audit.vue';
import Update from './components/Update.vue';
import Verify from './components/Verify.vue';

const page = 'firmwareVersion';
provide('page', page);
const tableRef = ref();
const handleState = ref('0');
const _fetchList = async (params: any) => {
  const res = await featchFirmwareList(params);
  res.rows.forEach((item: any) => {
    if (item.modelAlwaysVOS) {
      item.modelAlwaysVOS.forEach((model: any) => {
        model.typeName = `${model.typeName}(${model.modeName.length})`;
        model.modeName = model.modeName.map((name: any) => {
          return {
            typeName: name,
          };
        });
      });
    }
  });
  return { rows: [...res.rows], total: res.total || 0 };
};

const fileNames: TreeProps['fieldNames'] = {
  title: 'typeName',
  children: 'modeName',
};

const selectRows = ref<any[]>([]);
const rowSelection = computed<ProTableProps['rowSelection']>(() => {
  return {
    onChange(values, selectedRows) {
      selectRows.value = selectedRows;
    },
  };
});

const modelTreeData = ref([]);
const packgaeList = ref<{ label: string; value: string | number }[]>([]);
onMounted(() => {
  modelTree().then((res: any) => {
    modelTreeData.value = res.data;
  });
  pullPackageList({ deviceType: '2' }).then((res: any) => {
    packgaeList.value = listToOption(res.data, 'name', 'id');
  });
});
const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '固件版本ID',
    dataIndex: 'code',
    hideInSearch: true,
    fixed: 'left',
  },
  {
    title: '固件包版本',
    dataIndex: 'version',
    fixed: 'left',
  },
  {
    title: '更新类型',
    dataIndex: 'updateType',
    width: 120,
    valueEnum: appUpdateTypeEnum,
    customRender({ text }) {
      return (
        <Tag class={text == '1' ? 'ql' : 'zl'}>
          {appUpdateTypeEnum[text as keyof typeof appUpdateTypeEnum]}
        </Tag>
      );
    },
    fixed: 'left',
  },
  {
    title: '设备型号',
    dataIndex: 'modelAlwaysVOS',
    hideInSearch: true,
    width: 160,
  },
  {
    title: '设备型号',
    dataIndex: 'modelIds',
    hideInTable: true,
    customSearchRender(state) {
      return (
        <TreeSelect
          v-model:value={state.modelIds}
          fieldNames={{
            children: 'childs',
            label: 'model',
            value: 'modelId',
          }}
          placeholder='请选择'
          treeData={modelTreeData.value}
          treeCheckable={true}
          maxTagCount={1}
          allowClear={true}
        />
      );
    },
  },
  {
    title: '待升级软件版本',
    dataIndex: 'allowVersion',
    hideInSearch: true,
    // width: 150,
    customRender({ record }) {
      return (
        <span>{record.updateType == '1' ? '-' : `${record.allowVersion}`}</span>
      );
    },
  },
  {
    title: '版本说明',
    dataIndex: 'versionDesc',
    hideInSearch: true,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    hideInSearch: true,
  },
  {
    title: '审核状态',
    dataIndex: 'isAudit',
    width: 100,
    valueEnum: auditEnum,
    customRender({ text }) {
      return (
        <Tag color={text == '0' ? 'success' : 'warning'}>
          {auditEnum[text as keyof typeof auditEnum]}
        </Tag>
      );
    },
  },
  {
    title: '审核时间',
    dataIndex: 'auditTime',
    hideInSearch: true,
  },
  {
    title: '审核人',
    dataIndex: 'auditBy',
    hideInSearch: true,
  },
  {
    title: '是否启用',
    dataIndex: 'isEnable',
    width: 100,
    valueEnum: enableStatusEnum,
    customRender({ text }) {
      return (
        <Tag color={text == '0' ? 'success' : 'error'}>
          {enableStatusEnum[text as keyof typeof auditEnum]}
        </Tag>
      );
    },
    defaultValue: '0',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    width: 300,
  },
]);
const modalType = ref('info');
const modelAlwaysVOS = ref([]);
const items = computed<ProFormProps['items']>(() => {
  if (modalType.value === 'info' || modalType.value === 'audit') {
    return [
      {
        label: '',
        type: 'select',
        field: 'openAudit',
      },
    ];
  }
  return [
    {
      label: '更新类型',
      type: 'select',
      field: 'updateType',
      rules: [
        {
          required: true,
          message: '请选择更新类型',
          trigger: 'blur',
        },
      ],
      props: {
        disabled: modalType.value === 'edit',
        placeholder: '请选择更新类型',
        options: appUpdateTypeOption,
        onChange: (data) => {
          if (data == '1') {
            type.value = true;
          } else {
            type.value = false;
          }
        },
      },
    },
    {
      label: '下载地址',
      type: 'input',
      field: 'versionDowmloadUrl',
      rules: [
        {
          required: true,
          message: '请输入下载地址',
          trigger: 'blur',
        },
      ],
      props: {
        placeholder: '请输入下载地址',
      },
    },
    {
      label: '固件包版本',
      type: 'input',
      field: 'version',
      rules: [
        {
          required: true,
          trigger: 'blur',
          message: '请输入固件包版本',
        },
      ],
    },
    {
      label: 'MD5',
      type: 'input',
      field: 'md5',
      rules: [
        {
          required: true,
          message: '请输入MD5',
          trigger: 'blur',
        },
      ],

      props: {
        placeholder: '请输入MD5',
      },
    },
    {
      label: '待升级固件版本',
      type: 'input',
      field: 'allowVersion',
      rules: [
        {
          required: true,
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (formRef.value.getFieldsValue().updateType == '1') {
              return Promise.resolve();
            }
            if (!value) {
              return Promise.reject('请输入待升级固件版本');
            } else {
              return Promise.resolve();
            }
          },
        },
      ],
      customRender(formState) {
        return (
          <Input
            disabled={type.value}
            v-model:value={formState.allowVersion}
            placeholder='请输入待升级固件版本'
            name='allowVersion'
          ></Input>
        );
      },
    },

    {
      label: '固件包名',
      type: 'select',
      field: 'upgradeId',
      rules: [
        {
          required: true,
          message: '请选择固件包名',
          trigger: 'blur',
        },
      ],
      props: {
        placeholder: '请选择固件包名',
        options: packgaeList.value,
        onChange(value: any, option) {
          _getUpgradeDetail(value);
        },
      },
    },
    {
      label: '版本说明',
      type: 'textarea',
      field: 'versionDesc',
    },
    {
      label: '设备型号',
      type: 'input',
      field: 'modeltype',
      customRender(formState) {
        return (
          <Tree
            tree-data={modelAlwaysVOS.value}
            class={'tree'}
            field-names={fileNames}
          />
        );
      },
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
      colProps: {
        span: 18,
      },
    },
  ];
});
const _getUpgradeDetail = (value: any) => {
  getUpgradeDetail(value).then((res: any) => {
    res.data?.modelAlwaysVOS.forEach((model: any) => {
      model.typeName = `${model.typeName}(${model.modeName.length})`;
      model.modeName = model.modeName.map((name: any) => {
        return {
          typeName: name,
        };
      });
      modelAlwaysVOS.value = res.data.modelAlwaysVOS;
    });
  });
};
const { FormModal, open, formRef } = useFormModal({
  size: 'middle',
  column: 2,
  formProps: { wrapperCol: { span: 24 }, labelCol: { span: 6 } },
  onValuesChange(changeValues, formState, modalType) {
    if (changeValues.updateType == '1') {
      formState.allowVersion = '';
    }
  },
});
const type = ref(true);
const onAdd = async () => {
  modelAlwaysVOS.value = [];
  type.value = false;
  modalType.value = 'add';
  open({
    title: '新增',
    defaultValue: {},
    serviceApi: async (params: any): Promise<any> => {},
  });
};
const auditInfo = ref({});
const onUpdate = async () => {
  let response: any = await getFirmwareInfo(auditInfo.value.versionId);
  _getUpgradeDetail(response.data.upgradeId);
  modalType.value = 'edit';
  open({
    title: '编辑',
    column: 2,
    defaultValue: { ...(response.data as object) },
    onChangeModeType(modalType: any) {
      if (response.data.updateType == '1') {
        type.value = true;
      } else {
        type.value = false;
      }
    },
    serviceApi: async (params: any): Promise<any> => {},
  });
};

const onSubmit = async (params: any, visible: any) => {
  let api = modalType.value === 'add' ? addFirmware : updateFirmware;
  await api({ ...params, isEnable: '0' });
  sleep(() => tableRef.value.refresh());
  message.success('操作成功');
  visible.value = false;
};

const onAudit = async (record: any) => {
  auditInfo.value = record;
  modalType.value = 'audit';
  open({
    title: '审核',
    defaultValue: {
      ...record,
    },
    serviceApi: async (params: any): Promise<any> => {},
  });
};
const onSwitch = async (record: any) => {
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: `确认${record.isEnable == '0' ? '停用' : '启用'}当前项？`,
    onOk: async () => {
      await firmUpdateStatus({
        versionId: record.versionId,
        status: record.isEnable == '0' ? '1' : '0',
      });
      sleep(() => tableRef.value.refresh());
      message.success('操作成功');
    },
  });
};

const openVerify = ref(false);
const pushInfo = ref({});
const onPush = async (record: any) => {
  pushInfo.value = record;
  openVerify.value = true;
  // const res = await getSoftwarePush(record.versionId);
  // pushInfo.value = res.data as object;
  //
};

const onConfirm = async (visible: any) => {
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: `确认审核通过？`,
    onOk: async () => {
      await firmSubmitAudit({
        versionId: auditInfo.value.versionId,
        isAudit: '0',
      });
      sleep(() => tableRef.value.refresh());
      message.success('审核成功');
      visible.value = false;
    },
  });
};

const onLook = async (record: any) => {
  auditInfo.value = record;
  modalType.value = 'info';
  open({
    title: '查看',
    modalType: 'add',
    defaultValue: {
      ...record,
    },
    serviceApi: async (params: any): Promise<any> => {},
  });
};
const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};

const onDelete = async () => {
  const versionIds = selectRows.value.map((item) => item.versionId);
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: `确认删除当前项？`,
    onOk: async () => {
      await delFirmware(versionIds.join());
      sleep(() => tableRef.value.refresh());
      message.success('删除成功');
    },
  });
};

const verifyRef = ref();
const onVerify = async () => {
  verifyRef.value.submitForm();
};

const openUpdate = ref(false);
const updateInfo = ref({});
const updateLog = (data: any) => {
  openVerify.value = false;
  updateInfo.value = data;
  openUpdate.value = true;
  console.log(data);
};

const onCancel = (visible: any) => {
  if (modalType.value === 'add') {
    visible.value = false;
  } else {
    modalType.value = 'info';
  }
};
</script>
<style lang="scss">
.tree {
  :deep(.ant-tree) {
    background: none;
  }
}
.fireVersion_modal {
  .ant-modal .ant-modal-content .ant-modal-body {
    min-height: 502px;
  }
}
</style>
